/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-unused-vars */

// ######### 艺术照模板 #######
// 1、遍历完对应的目录
// 2、查询或者保存目录名，得到 categoryId，建立缓存map减少查库
// 3、创建模板，得到templateId，得到list文件
// 4、创建文件记录

const fs = require('fs');
const axios = require('axios');
const ProgressBar = require('progress');
const Path = require('path');
const FormData = require('form-data');
const { async } = require('rxjs');

const authorization =
  'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3ZWl4aW5fb3BlbklkIjoib3cwdEk1VWVtN18wODNOYXZQQlBIR0RBQXlUZyIsImlwIjoiMTIwLjIyNy4zNy4xMTEiLCJ1c2VySWQiOiI2YmJkOWM4Yi0yMTA4LTQzODAtOTM0My0yODk2OWQyMTU3ZmMiLCJpYXQiOjE2OTk0NTE1NjMsImV4cCI6MTcwMjA0MzU2M30.5QoR33C-xfxlobmr4fE5Q26B7pIwTnLcbv1B1xjdyjw';
// js去实现表单查询，创建模板，上传文件，生成对应记录

// 调三个接口即可
// 1 遍历对应目录
let m = 0;
let dirMap = {};
let categoryMap = {};
let isTest = false;
let error =[]

async function getFilesForPic(dir) {
  const fileDirs = fs.readdirSync(dir);
  for (let i = 0; i < fileDirs?.length; i++) {
    const tempFile = Path.join(dir, fileDirs[i]);
    const fileStat = fs.statSync(tempFile);
    if (fileStat.isDirectory()) {
      //获取各个分类目录名
      const tempDir = Path.join(dir, fileDirs[i]);
      if (!isTest) {
        const dirObj = await updateDir(fileDirs[i]);
        dirMap[fileDirs[i]] = dirObj;
      } else {
        dirMap[fileDirs[i]] = {};
      }
      getFilesForPic2(tempDir);
    }
  }

  console.log(error)
}

async function getFilesForPic2(dir) {
  const fileDirs = fs.readdirSync(dir);
  for (let i = 0; i < fileDirs?.length; i++) {
    const tempFile = Path.join(dir, fileDirs[i]);
    const fileStat = fs.statSync(tempFile);
    if (fileStat.isFile()) {
      // 全部上传
      // if (fileDirs[i] === '.DS_Store') {
      //   console.log(1);
      // } else {
      //   const filePath = Path.join(dir, fileDirs[i]);
      //   m++;
      //   const dirName = Path.dirname(filePath);
      //   const fileName = Path.basename(dirName);
      //   console.log(filePath,fileName, categoryMap[fileName]);
      //   const response = await uploadScript(filePath, categoryMap[fileName]);
      //   console.log('模板：' + fileName + '第' + m + '张', response.id);
      // }
    } else {
      const tempDir = Path.join(dir, fileDirs[i]);

      const dirName = Path.dirname(tempDir);
      const predir = Path.basename(dirName);
      if (!isTest) {
        //1、 传错了的 翻车补救

        // await delTemplate("deleteOSS",dirMap[predir], tempDir);

        // 2、没删除掉的
        const isGo = await delTemplate(
          'deleteOSSForNumber',
          dirMap[predir],
          tempDir,
        );
        if (isGo) {
          const response = await creatTemplate(dirMap[predir], tempDir);
          categoryMap[fileDirs[i]] = response;
          try {
            getRealFile2(tempDir);
          } catch (error) {}
        }

        // const response = await creatTemplate(dirMap[predir], tempDir);
        // categoryMap[fileDirs[i]] = response;
        // try {
        //   getRealFile(tempDir);
        // } catch (error) {}
      } else {
        categoryMap[fileDirs[i]] = {};
        try {
          getRealFile(tempDir);
        } catch (error) {}
      }
      // 全部上传
      // getFilesForPic2(tempDir);
      // 部分上传
      // getRealFile(tempDir);
    }
  }
}

// 单独取数据
async function getRealFile(dir) {
  //得到所有文件 不需要遍历获取随机取索引
  const fileName = Path.basename(dir);

  const fileDirs = fs.readdirSync(dir);
  if(fileDirs.length<4){
    error.push(categoryMap[fileName].id)
    return
  }
  const count = fileDirs.length - 4;
  //索引随机性问题 用文件名
  const keys = [2, 3, 4];
  let temp1 = Math.round(Math.random() * count) + 4;
  while (keys.includes(temp1) && temp1 != 4) {
    temp1 = Math.round(Math.random() * count) + 4;
  }
  if (temp1 != 4) {
    keys.push(temp1);
  }
  let temp2 = Math.round(Math.random() * count) + 4;
  while (keys.includes(temp2) && temp2 != 4) {
    temp2 = Math.round(Math.random() * count) + 4;
  }
  if (temp2 != 4) {
    keys.push(temp2);
  }
  const promises = [];
  for (let index = 0; index < keys.length; index++) {
    const i = keys[index];
    const filePath = Path.join(
      dir,
      fileDirs.find((item) => {
        const temp = Path.basename(item, Path.extname(item));
        if (i == temp) {
          return item;
        }
      }),
    );
    console.log(filePath, fileName, categoryMap[fileName]);
    const p = new Promise((resolve) => {
      setTimeout(
        async () => {
         
          if (!isTest) {
            const response = await uploadScript(
              filePath,
              categoryMap[fileName],
              i
            );
            m++;
            console.log(
              '模板：' + fileName + '第' + m + '张',
              response?.data?.id,
            );
            resolve(true);
          } else {
            m++;
            console.log(
              '模板：' + fileName + '第' + m + '张',
              Path.basename(filePath),
            );
            resolve(true);
          }
        },
        Math.random() * 200 + 100,
      );
    });
    promises.push(p);
  }
  const coverRes = new Promise((resolve) => {
    // 封面处理
    setTimeout(
      async () => {
        const filePath = Path.join(dir, '_cover.jpg');
       
        const dirName = Path.dirname(filePath);
        const fileName = Path.basename(dirName);
        if (!isTest) {
          const response = await uploadScript(
            filePath,
            categoryMap[fileName],
            'cover',
          );
          m++;
          console.log('模板封面：' + fileName + '第' + m + '张', response?.data?.id);
          resolve(true);
        } else {
          console.log(
            '模板封面：' + fileName + '第' + m + '张',
            Path.basename(filePath),
          );
          resolve(true);
        }
      },
      Math.random() * 200 + 100,
    );
  });
  if (coverRes) {
    Promise.all(promises)
      .then(function (posts) {})
      .catch(function (reason) {
        console.log('出错了', reason);
      });
  }
}
async function getRealFile2(dir) {
  //得到所有文件 不需要遍历获取随机取索引

  const fileDirs = fs.readdirSync(dir);
  //索引随机性问题 用文件名

  const promises = [];
  for (let index = 0; index < fileDirs.length; index++) {
    const i = fileDirs[index];
    const filePath = Path.join(dir, i);
    const fileName = Path.basename(dir);
    console.log(filePath, fileName, categoryMap[fileName]);
    const p = new Promise((resolve) => {
      setTimeout(
        async () => {
          m++;
          if (!isTest) {
            const response = await uploadScript(
              filePath,
              categoryMap[fileName],
            );
            console.log(
              '模板：' + fileName + '第' + m + '张',
              response?.data?.id,
            );
            resolve(true);
          } else {
            console.log(
              '模板：' + fileName + '第' + m + '张',
              Path.basename(filePath),
            );
            resolve(true);
          }
        },
        Math.random() * 200 + 100,
      );
    });
    promises.push(p);
  }

  Promise.all(promises)
    .then(function (posts) {})
    .catch(function (reason) {
      console.log('出错了', reason);
    });
}

//  2创建属性分类
async function updateDir(dirName) {
  //缓存判断
  if (Object.keys(dirMap).includes(dirName)) {
    return dirMap[dirName];
  }
  const params = {
    name: dirName,
    description: '',
    parentId: '4',
  };
  var url = 'http://localhost:3009/api/templateCategory/addForName';
  const config = {
    headers: {
      'Content-Type': 'application/json',
      authorization: authorization,
    },
  };
  return new Promise((resolve) => {
    axios
      .post(url, params, config)
      .then(async function (response) {
        console.log(response.data);
        resolve(response.data.data);
      })
      .catch(function (error) {
        console.log(error);
      });
  });
}
// 3 创建模板记录
async function creatTemplate(dirObj, filePath) {
  const fileName = Path.basename(filePath);
  var name = fileName;
  name = name.length > 6 ? name.substring(0, 6) : name;

  const params = {
    categoryId: dirObj.id,
    title: name, //取文件名前4个字
  };

  var url = 'http://localhost:3009/api/template/addForName';
  const config = {
    headers: {
      'Content-Type': 'application/json',
      authorization: authorization,
    },
  };

  return new Promise((resolve) => {
    axios
      .post(url, params, config)
      .then(async function (response) {
        // console.log(response.data);

        if (response.data.code == 0) {
          resolve(response.data.data);
        } else {
          resolve({});
        }
      })
      .catch(function (error) {
        console.log(error);
      });
  });
}
async function delTemplate(action = 'deleteOSSForNumber', dirObj, filePath) {
  const fileName = Path.basename(filePath);
  var name = dirObj.name + fileName;
  name = name.length > 6 ? name.substring(0, 6) : name;
  const params = {
    title: name, //取文件名前4个字
  };
  // c1830a53-8a9f-4bfc-8b8e-e5fca9977c61
  var url = `http://localhost:3009/api/file/${action}`;
  const config = {
    headers: {
      'Content-Type': 'application/json',
      authorization: authorization,
    },
  };

  return new Promise((resolve) => {
    axios
      .post(url, params, config)
      .then(async function (response) {
        // console.log(response.data);

        if (response.data.code == 0) {
          resolve(response.data.data == 'ok');
        } else {
          resolve({});
        }
      })
      .catch(function (error) {
        console.log(error);
      });
  });
}

async function deleteOSSByOne(action = 'deleteOSSByOne', dirObj, filePath) {

  
  const params = {
    id: "c1830a53-8a9f-4bfc-8b8e-e5fca9977c61", //取文件名前4个字
  };
  // c1830a53-8a9f-4bfc-8b8e-e5fca9977c61
  var url = `http://localhost:3009/api/file/${action}`;
  const config = {
    headers: {
      'Content-Type': 'application/json',
      authorization: authorization,
    },
  };

  return new Promise((resolve) => {
    axios
      .post(url, params, config)
      .then(async function (response) {
        console.log(response.data);

        if (response.data.code == 0) {
          resolve(response.data.data == 'ok');
        } else {
          resolve({});
        }
      })
      .catch(function (error) {
        console.log(error);
      });
  });
}

// 4 上传文件
async function uploadScript(filePath, data, name) {
  var url = 'http://localhost:3009/api/file/uploadScript';

  const formData = new FormData();

  formData.append('file', fs.createReadStream(filePath));
  formData.append('categoryId', data.categoryId);
  formData.append('templateId', data.id);
  // formData.append('templateId', "e8849fe0-d9c0-4eb7-9661-aafc6745aff6");
  formData.append('name', name || new Date().getTime());
  const config = {
    headers: {
      'Content-Type': 'multipart/form-data;boundary=' + new Date().getTime(),
      authorization: authorization,
    },
  };
  const progressBar = new ProgressBar(
    `Uploading ${data.title} [:bar] :percent`,
    {
      total: fs.statSync(filePath).size,
      width: 40,
      complete: '=',
      incomplete: ' ',
    },
  );
  const response = await axios.post(url, formData, {
    headers: config.headers,
    onUploadProgress: (progressEvent) => {
      progressBar.tick(progressEvent.loaded);
    },
  });
  try {
    console.log(`Upload complete: ${response.data?.data?.id}`);
  } catch (error) {}
  return response?.data;
}
// getFilesForPic('/Users/a888/Downloads/tips/image-splider/result/pic');
// 测试一下
getFilesForPic('/Users/a888/Downloads/tips/image-splider/result/sfz');


